import { createApp } from 'vue';
import store from '@/store';
import DataDict from '@/utils/dict/index.js';
import { getDicts } from '@/api/system/dict/data';

function searchDictByKey(dict, key) {
  if (key == null || key === "") {
    return null;
  }
  try {
    for (let i = 0; i < dict.length; i++) {
      if (dict[i].key === key) {
        return dict[i].value;
      }
    }
  } catch (e) {
    return null;
  }
}

function install(app) {
  app.use(DataDict, {
    metas: {
      '*': {
        labelField: 'dictLabel',
        valueField: 'dictValue',
        request(dictMeta) {
          const storeDict = searchDictByKey(store.getters.dict, dictMeta.type);
          if (storeDict) {
            return Promise.resolve(storeDict);
          } else {
            return getDicts(dictMeta.type).then(res => {
              store.dispatch('dict/setDict', { key: dictMeta.type, value: res.data });
              return res.data;
            }).catch(error => {
              throw error;
            });
          }
        },
      },
    },
  });
}

export default {
  install,
};